package com.han.demo.utils;

import com.han.demo.entity.User;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Jackson工具类
 *
 * @author hanjiale
 * @create 2021-08-25 2:18 PM
 **/
@Slf4j
public class JsonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 对象字段全部列入
        objectMapper.setSerializationInclusion(Inclusion.NON_DEFAULT);

        // 取消默认转换timestamps形式
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);

        // 忽略空bean转json的错误
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);

        // 统一日期格式yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        // 忽略在json字符串中存在,但是在java对象中不存在对应属性的情况
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }

    /**
     * Object转json字符串
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String obj2String(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse object to String error",e);
            return null;
        }
    }

    /**
     * Object转json字符串并格式化美化
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String obj2StringPretty(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse object to String error",e);
            return null;
        }
    }

    /**
     * string转object
     * @param str json字符串
     * @param clazz 被转对象class
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String str,Class<T> clazz){
        if (StringUtils.isEmpty(str) || clazz == null){
            return null;
        }
        try {
            return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
        } catch (IOException e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }

    /**
     * string转object
     * @param str json字符串
     * @param typeReference 被转对象引用类型
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String str, TypeReference<T> typeReference){
        if (StringUtils.isEmpty(str) || typeReference == null){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class)? str :objectMapper.readValue(str,typeReference));
        } catch (IOException e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }

    /**
     * string转object 用于转为集合对象
     * @param str json字符串
     * @param collectionClass 被转集合class
     * @param elementClasses 被转集合中对象类型class
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
        try {
            return objectMapper.readValue(str,javaType);
        } catch (IOException e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }

    public static void main(String[] args) {
        //测试对象转json
        User user = new User();
        user.setId(1);
        user.setName("韩佳乐");
        user.setAge(18);
        user.setRemark("测试");
        String obj2String = JsonUtil.obj2String(user);
        System.out.println("对象转json结果：" + obj2String);

        //测试美化后的json字符串
        String obj2StringPretty = JsonUtil.obj2StringPretty(user);
        System.out.println("对象转json美化后的结果："+ obj2StringPretty );

        //测试json字符串转对象
        String str = "{\"id\":2,\"name\":\"周梦\",\"remark\":\"美化\"}";
        User user1 = JsonUtil.string2Obj(str, User.class);
        System.out.println("json字符串转对象的结果：" + user1.toString());

        //使用TypeReference转换复杂对象
        User u1 = new User();
        u1.setName("aaa");
        u1.setId(1);
        User u2 = new User();
        u2.setName("bbb");
        u2.setId(2);
        List<User> userList = Lists.newArrayList();
        userList.add(u1);
        userList.add(u2);
        String userListStr = JsonUtil.obj2StringPretty(userList);
        List<User> userListObj = JsonUtil.string2Obj(userListStr, new TypeReference<List<User>>() {});
        System.out.println("TypeReference转换复杂对象的结果" + userListObj);

        // 更简单直接的复杂对象转换方法
        User u3 = new User();
        u3.setName("aaa");
        u3.setId(1);
        User u4 = new User();
        u4.setName("bbb");
        u4.setId(2);
        List<User> userList2 = Lists.newArrayList();
        userList2.add(u1);
        userList2.add(u2);
        String userListStr2 = JsonUtil.obj2StringPretty(userList);
        // List<User> userListObj = JsonUtil.string2Obj(userListStr2, new TypeReference<List<User>>() {});
        // 依次传入集合以及集合中对象类型的class
        List<User> userListObj2 = JsonUtil.string2Obj(userListStr,List.class,User.class);
        System.out.println("更简单直接的复杂对象转换方法的结果：" + userListObj2);
    }
}
